package cn.lml.lession.auth.config;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;


@Component("customAuthenticationFailureHandler")
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

	private final static Logger logger = LoggerFactory.getLogger(CustomAuthenticationFailureHandler.class);

	@Autowired
	private AuthProperties authProperties;
	
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		logger.info("登录失败,errorMsg={}",exception.getMessage());
		String url=authProperties.getAuthFailureUrl();
		if(StringUtils.isBlank(url)){
			url=request.getHeader("Referer");
		}
		if(StringUtils.isNotBlank(url)){
			super.setDefaultFailureUrl(url.substring(0,url.indexOf("?")==-1?url.length():url.indexOf("?"))+"?error="+new String(exception.getMessage().getBytes(),"ISO-8859-1"));
		}
		super.onAuthenticationFailure(request, response, exception);
	}

}
